<template>
  <u-popup v-model="show" class="popup" mode="bottom" @close="popupclose">
    <view class="goods__container">
      <view class="goods_info">
        <view class="goods__img-container" v-if="data.goodsPictureList">
          <u-image
            class="goods_img"
            width="230rpx"
            height="230rpx"
            border-radius="6"
            :src="goodsImageUrl"
          ></u-image>
        </view>

        <view class="info">
          <view class="goods-name__container">
            {{ data.goodsName }}
          </view>
          <!-- 仅在单规格且无阶梯价时出现 -->
          <view
            v-if="(!(data.ladderPriceList || []).length) && ((skuInfo.specificationSkuList || []).length <= 1)"
            class="price"
          >
            <text style="color: #ff1010; font-size: 20rpx">{{
              $store.getters.currency
            }}</text>
            {{ (+priceMin).toFixed(2) }}
          </view>

          <view v-else class="price">
            <text style="color: #ff1010; font-size: 20rpx">{{ $store.getters.currency }}</text>
            {{ priceMin.toFixed(2) }}
            <text v-if="priceMin !== priceMax">~</text>
            <text v-if="priceMin !== priceMax" style="color: #ff1010; font-size: 20rpx">{{ $store.getters.currency }}</text>
            <text v-if="priceMin !== priceMax">{{ priceMax.toFixed(2) }}</text>
          </view>
        </view>
      </view>

      <view class="format__all-container">
        <view 
          v-if="(
            (skuInfo.specificationMainList || []).length >= 1 && (skuInfo.specificationOtherList || []).length > 1
          )"
          class="format__tab-container"
        >
          <Tabs :list="skuInfo.specificationMainList" :current-tab="currentTab" @click="onClickTabItem" />
        </view>

        <scroll-view class="format__scroll-container" scroll-y>
          <SpecItem
            v-for="item in skuList"
            :key="item.id"
            :value="selectedSkuObj[item.id].count"
            :unit="data.currencySymbol"
            :data="item"
            :disabled="selectedSkuObj[item.id].isMixUpDisabled"
            :is-show-first-name="(skuInfo.specificationMainList || []).length >= 1 && (skuInfo.specificationOtherList || []).length <= 1"
            :is-show-price="!(data.ladderPriceList && data.ladderPriceList.length)"
            @change="onChangeSkuCount"
            @click="onClickSkuItem"
          />
        </scroll-view>

        <view class="format__total">
          <view class="total">
            {{ $t('locales.all') }} <text class="count"> {{ allCount }} </text> {{ $t('locales.items') }}
          </view>

          <view class="all-cost">
            {{ data.currencySymbol }} {{ allPrice.toFixed(2) }}
          </view>
        </view>
      </view>

      <!-- <view class="goods_num">
        <view>{{ $t('locales.purchaseQuantity') }}</view>
        <u-number-box v-model="count" @change="valChange"></u-number-box>
      </view> -->
      <u-button
        type="primary"
        ripple
        :disabled="placedisabled"
        :custom-style="btnStyle"
        @click="placeOrder"
      >
        {{ $t('locales.determine') }}
      </u-button>
    </view>
  </u-popup>
</template>

<script>
import Tabs from '@/components/tabs'
import SpecItem from '@/components/specItem'
import { generateOrder, addShoppingCart, updateSku } from '@/api/http/order'
export default {
  components: {
    Tabs,
    SpecItem
  },

  props: {
    value: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {}
    },
    type: {
      // 1 立即购买 2 加入购物车 3 修改规格
      type: [String, Number],
      default: ''
    },

    skuInfo: {
      type: Object,
      default: () => ({
        specificationMainList: [],
        specificationOtherList: [],
        specificationSkuList: []
      })
    },

    routerParams: {
      type: Object,
      default: () => {}
    }
  },

  computed: {
    skuList() {
      // if (!this.skuInfo.specificationOtherList) return

      if ((this.skuInfo.specificationMainList || []).length >= 1 && (this.skuInfo.specificationOtherList || []).length <= 1) {
        return this.skuInfo.specificationSkuList
      }

      // 如果没有子规格 则返回所有的 sku
      if (!(this.skuInfo.specificationOtherList || []).length) {
        return this.skuInfo.specificationSkuList
      }

      // 如果 主规格 和 子规格 长度均为 1 则返回所有 sku
      if ((this.skuInfo.specificationMainList || []).length <= 1) {
        return this.skuInfo.specificationSkuList
      }

      // 如果 主规格 大于 1 则返回该筛选该 主规格 的 SKU
      if (this.skuInfo.specificationMainList.length > 1) {
        return this.skuInfo.specificationSkuList.filter(current => 
          current.specificationMainName === this.skuInfo.specificationMainList[this.currentTab].specificationMainName
        )
      }
    },

    allCount() {
      return Object.values(this.selectedSkuObj).reduce((prev, current) => prev += current.count, 0)
    },

    allPrice() {
      let price = 0
      let hasLadderPrice = false
      const ladderPriceList = this.data.ladderPriceList

      if (ladderPriceList && ladderPriceList.length) {
        hasLadderPrice = true
        const found = ladderPriceList.findIndex(current => {
          return +current.startQty >= +this.allCount
        })

        if (found > -1) {
          const index = found === 0 ? found : found - 1
          price = ladderPriceList[index].price
        } else {
          price = ladderPriceList[ladderPriceList.length - 1].price
        }
      }

      return Object.values(this.selectedSkuObj).reduce((prev, current) => {
        return prev += current.count * (hasLadderPrice ? price : current.price)
      }, 0)
    },

    priceMin() {
      if ((this.data.ladderPriceList || []).length) {
        const count = (this.data.ladderPriceList || []).map(current => +current.price)
        return Math.min.call(null, ...count)
      }

      if ((this.skuInfo.specificationSkuList || []).length) {
        const count = (this.skuInfo.specificationSkuList || []).map(current => +current.price)
        return Math.min.call(null, ...count)
      }
    },

    priceMax() {
      if (this.data.ladderPriceList.length) {
        const count = (this.data.ladderPriceList || []).map(current => +current.price)
        return Math.max.call(null, ...count)
      }

      if (this.skuInfo.specificationSkuList.length) {
        const count = (this.skuInfo.specificationSkuList || []).map(current => +current.price)
        return Math.max.call(null, ...count)
      }
    }
  },

  watch: {
    value(val) {
      this.show = val
      this.goodsImageUrl = this.data.goodsPictureList?.[0]?.pictureUrl
    },
    show(val) {
      this.$emit('input', val)
    },
    data(val) {
      if (this.data.price) {
        this.data.priceitem = this.data.price
      } else {
        this.data.priceitem = this.data.ladderPriceList[0].price
      }

      this.goodsImageUrl = this.data.goodsPictureList?.[0]?.pictureUrl
    },

    'skuInfo.specificationSkuList'() {
      this.selectedSkuObj = this.skuInfo.specificationSkuList.reduce((prev, current) => {
        prev[current.id] = {
          count: this.selectedSkuObj[current.id]?.count || 0,
          price: current.price,
          skuId: current.id
          // isMixUpDisabled: false
        }
        return prev
      }, {})
    }
  },
  data() {
    return {
      show: false,
      btnStyle: {
        borderRadius: '0'
      },
      specsBtnStyle: {
        margin: '0 5rpx'
      },
      count: 1,
      priceitem: '',
      placedisabled: false,

      currentTab: 0,
      
      selectedSkuObj: {},

      goodsImageUrl: ''
    }
  },

  methods: {
    popupclose() {
      this.count = 1
      if (this.data.price) {
        this.data.priceitem = this.data.price
      } else {
        this.data.priceitem = this.data.ladderPriceList[0].price
      }

      // this.goodsImageUrl = this.data.goodsPictureList?.[0]?.pictureUrl
    },
    valChange(e) {
      if (e.value === 0) {
        this.placedisabled = true
        uni.showToast({
          icon: 'none',
          title: '至少购买一件商品'
        })
        return
      } else {
        this.placedisabled = false
      }
      const ladderlength = this.data.ladderPriceList
      if (ladderlength.length === 0) return
      const found = ladderlength.find((current, index) => {
        const next = ladderlength[index + 1]
        if (!next) {
          return true
        }
        if (next.startQty > e.value && e.value >= current.startQty) {
          return true
        }
      })
      this.data.priceitem = found.price
    },
    // 下单
    placeOrder() {
      const values = Object.values(this.selectedSkuObj)
      // const keys = Object.keys(this.selectedSkuObj)
      const params = {
        count: values.filter(current => current.count > 0).map(current => current.count),
        goodsId: this.data.id,
        domainPrefix: this.$store.getters.domainPrefix,
        skuIds: values.filter(current => current.count > 0).map(current => current.skuId)
      }

      const allCount = values.reduce((prev, current) => {
        prev += current.count
        return prev
      }, 0)

      console.log(this.routerParams)

      switch (this.type) {
        // 立即购买
        case 1:
          if(allCount < this.data.startingQuantity) {
            uni.showToast({
              icon: 'none',
              title: this.data.startingQuantity + this.$t('locales.goodsCountNeedMoreThan')
            })
          } else {
            this.show = false
          // 跳转订单预览页面
          uni.navigateTo({
            url:
              '/pages/order/preview/index?isQuickBuy=1&count=' +
              params.count.join(',') +
              '&id=' +
              params.goodsId +
              '&domainPrefix=' +
              this.data.domainPrefix +
              '&skuIds=' +
              params.skuIds.join(',') + 
              '&purchaseId=' + 
              this.routerParams.purchaseId || ''
            })
          }
          break
        // 加入购物车
        case 2:
          if (allCount <= 0) {
            uni.showToast({
              icon: 'none',
              title: this.$t('locales.goodsCountLessThanOne')
            })

            return
          }

          addShoppingCart({
            // ...params
            countList: params.count,
            goodsId: this.data.id,
            skuIds: params.skuIds,
            from: this.routerParams.purchaseId || ''
          }).then((res) => {
            if (res.code === 200) {
              this.show = false

              Object.values(this.selectedSkuObj).forEach(current => current.count = 0)
            }
            uni.showToast({
              icon: 'none',
              title: res.message
            })
          })
          break
      }
    },

    onChangeCurrentTab(current) {
      this.goodsImageUrl = current.pictureUrl
      this.currentTab = current
    },

    onChangeSkuCount(data, count) {

      if (this.type === 1) {
        if (!this.data.isMixUp) {
          // 判断是否有某个商品已经选中了
          const found = Object.keys(this.selectedSkuObj).find(current => this.selectedSkuObj[current].count !== 0)

          if (found) {
            if (+data.id !== +found) {
              uni.showToast({
                title: this.$t('locales.skuCategoryOneOnly'),
                icon: 'none'
              })
            }
          }

          Object.values(this.selectedSkuObj).forEach(current => this.$set(current, 'count', 0))
        }
      }

      this.onClickSkuItem(data)

      this.selectedSkuObj[data.id] = {
        ...this.selectedSkuObj[data.id],
        count
      }
    },

    onClickTabItem({ index, item }) {
      this.goodsImageUrl = item.pictureUrl
      this.currentTab = index
    },

    onClickSkuItem(item) {
      const { specificationMainName } = item

      const found = this.skuInfo.specificationMainList.find(current => current.specificationMainName === specificationMainName)

      if (found) {
        this.goodsImageUrl = found.pictureUrl
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.goods__container {
  // padding-top: 30rpx;
}

.goods_info {
  padding: 20rpx;
  width: 100%;
  min-height: 214rpx;
  position: relative;
  border-bottom: 1px solid #eeeeee;
  display: flex;
  .goods__img-container {
    position: absolute;
    top: -50rpx;
    background: #fff;

    .goods_img {
      // top: -50rpx;
      border: 1px solid #eee;
    }
  }
  
  .info {
    flex: 1;
    padding-left: 254rpx;
    .price {
      color: #ff1010;
      // font-weight: 700;
      font-size: 38rpx;
    }
    .price::before {
      font-size: 22rpx;
      font-weight: 400;
    }
    .item {
      color: #222;
      font-size: 24rpx;
    }

    .goods-name__container {
      width: 396rpx;
      font-size: 30rpx;
      line-height: 35rpx;
      margin-bottom: 34rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      color: #333;
    }
  }
}
.specs_box {
  margin-bottom: 20rpx;
  padding: 0 15rpx;
  .specs_name {
    line-height: 60rpx;
    padding-left: 5rpx;
  }
  .specs_list {
    line-height: 60rpx;
  }
}
.goods_num {
  height: 110rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
  box-sizing: border-box;
  border-top: 1px solid #eeeeee;
}

.format__all-container {
  .format__scroll-container {
    height: 529rpx;
    // padding-left: 19rpx;
  }

  .format__total {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 19rpx 31rpx;
    border-top: 1rpx solid #e0e0e0;
    font-size: 28rpx;

    .total {
      margin-right: 22rpx;
    }

    .count, .all-cost {
      color: #E02F26;
    }

    .count {
      margin: 0 4rpx;
    }
  }
}
</style>

<style lang="scss">
/deep/ .u-tabs .uni-scroll-view {
  overflow: auto hidden!important;
}

.popup /deep/ .uni-scroll-view {
  overflow: visible visible!important;
}

.format__scroll-container /deep/ .uni-scroll-view {
  overflow: hidden auto!important;
}
</style>
